import {
  getToken,
  setToken,
  removeToken,
  setRoleId,
  setUserName,
  removeRoleId,
  removeUserName,
  getRoleId, getUserName
} from '@/utils/auth'
import http from '@/utils/http-request'
const getDefaultState = () => {
  return {
    token: getToken(),
    roleId: getRoleId(),
    userName: getUserName()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLE_ID: (state, roleId) => {
    state.roleId = roleId
  },

  SET_USER_NAME: (state, userName) => {
    state.userName = userName
  }
}

const actions = {
  login({ commit }, userInfo) {
    const params = {
      account: userInfo.account,
      password: userInfo.password
    }
    return new Promise((resolve, reject) => {
      http.post('register/login', params).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_ROLE_ID', data.roleId)
        commit('SET_USER_NAME', data.name)
        setToken(data.token)
        setRoleId(data.roleId)
        setUserName(data.name)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      removeRoleId()
      removeUserName()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

